package top.dimples.controller.admin;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import top.dimples.common.ApiResponse;
import top.dimples.common.Consts;
import top.dimples.common.Status;
import top.dimples.model.Image;
import top.dimples.service.ImageService;
import top.dimples.vo.common.PageResult;
import top.dimples.vo.image.ImageListVO;
import top.dimples.vo.image.ImageUploadVO;

/**
 * @author Dimples_YJ
 * @date 2021/12/10
 */
@Api(tags = "后台接口")
@RestController("/admin/image")
public class ImageController {

    @Autowired
    private ImageService imageService;

    @ApiOperation(value = "图片列表", response = PageResult.class)
    @GetMapping("/list")
    public ApiResponse imageList(ImageListVO imageListVO) {
        QueryWrapper<Image> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderBy(StrUtil.isNotEmpty(imageListVO.getOrderBy()) && StrUtil.isNotEmpty(imageListVO.getAsc()), Consts.ASC.equals(imageListVO.getAsc()), imageListVO.getOrderBy());
        IPage<Image> page = imageService.page(new Page<>(imageListVO.getPageNum(), imageListVO.getPageSize()), queryWrapper);
        IPage<ImageUploadVO> imageList = page.convert(image -> Convert.convert(ImageUploadVO.class, image));
        PageResult<ImageUploadVO> result = PageResult.startPage(imageList);
        return ApiResponse.ofSuccess(result);
    }

    @ApiOperation(value = "删除图片")
    @DeleteMapping("/remove/{id}")
    public ApiResponse deleteImage(@PathVariable("id") String id) {
        return imageService.deleteImageById(id)
                ? ApiResponse.ofSuccess()
                : ApiResponse.of(Status.ERROR.getCode(), "删除失败", null);
    }


}
